package com.example.demo.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demo.service.UserInfoService;
import com.example.demo.util.NoAuthorization;
import com.example.demo.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //此方法内容测试时暂注掉
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            //跳过跨域中的OPTINONS请求
            return true;
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            boolean isContentNoAuth = handlerMethod.getMethod().isAnnotationPresent(NoAuthorization.class);
            if (isContentNoAuth) {
                return true;
            }
        }
        String token = request.getHeader("token");
        if (StrUtil.isNotEmpty(token)) {
            UserInfo userInfo = userInfoService.queryUserByToken(token);
            if (ObjectUtil.isNotEmpty(userInfo)) {
                MyRequestHalper.setThreadLocal(userInfo);
                return true;
            }
        }
        /*
         *//*
           观察被拦截的url
         *//*
        //log.info(request.getRequestURL().toString());
        *//*   if (StrUtil.containsAny(request.getRequestURL(), "/css","/js","/img","index.html")) {
            return true;
        }*//*
        //RequestDispatcher rd = request.getRequestDispatcher("/index.html");
        //Update by zhangfc 2021年12月21日 08:10:15 此处代表请求转发
        // rd.forward(request, response);
        response.sendRedirect("/index.html");*/
        return true;
    }
}
